<template>
  <div class="info_main mt-5 ml-5">
    <!--    搜素框  -->
    <div class="row" >
      <div class="col-md-10">
        <el-input  type="text"
                   v-model="findName"
                   style="width: 500px;"
                   placeholder="请输入管理员名称..."
                   clearable
                   @keyup.enter.native="searchByName">
        </el-input>
        <el-button type="primary" icon="el-icon-search" @click="searchByName()" class="ml-3" plain>搜索</el-button>
        <el-button type="info" icon="el-icon-delete" @click="clearFindInput()" class="ml-3">重置</el-button>
      </div>
    </div>
    <!--      添加按钮-->
    <div class="mt-2" >
      <el-button type="primary" @click="addOpen()" plain><i class="el-icon-plus" ></i>创建</el-button>
      <el-button @click="toggleSelection()">取消选择</el-button>
      <el-button type="danger" @click="handleMultipleDelete">批量删除</el-button>
    </div>
    <div class="show_data mt-2">
      <el-table
          ref="multipleTable"
          v-horizontal-scroll="'always'"
          show-overflow-tooltip
          :data="showData"
          style="width: 100%"
          :cell-style="{color: '#666', fontFamily: 'Arial',fontSize:'17px'}"
          :header-cell-style="{background:'whitesmoke', fontFamily:'Helvetica',fontSize:'20px'}"
          height="700"
          @selection-change="handleSelectionChange"
          tooltip-effect="dark"
          :default-sort = "{prop: 'date', order: 'descending'}">
        <el-table-column
            type="selection"
            width="130">
        </el-table-column>
        <el-table-column
            fixed
            prop="admin_register_time"
            label="创建时间"
            width="300">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ scope.row.admin_register_time }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="admin_name"
            label="管理员名"
            width="300">
        </el-table-column>
        <el-table-column
            prop="admin_account"
            label="管理员账号"
            width="240">
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="250">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="edit(scope.$index, scope.row)">
              <span class="btnfontClass" >编辑</span>
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">
              <span class="btnfontClass" >删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--    分页-->
      <div class="pagin mt-5 mb-5">
        <el-pagination
            @current-change="handleCurrentChange"
            :current-page="adminContainerPage"
            :page-size="adminContainerSize"
            layout="total,prev, pager, next"
            :total=total>
        </el-pagination>
      </div>

      <!--编辑弹窗-->
      <el-dialog
          title="编辑管理员信息"
          :visible.sync="editdialogVisible"
          width="40%"
          @close="handleCloseEdit">

        <!--        编辑表单-->
        <el-form ref="Editform" :model="Editform" label-width="100px" :before-close="closeDivEdit">

          <el-form-item label="账号：" :label-width="formLabelWidth" prop="admin_account">
            <el-input
                disabled
                show-word-limit
                v-model="Editform.admin_account"
                maxlength="10"
                type="text">
            </el-input>
          </el-form-item>

          <el-form-item label="名称：" :label-width="formLabelWidth" prop="admin_name">
            <el-input
                show-word-limit
                v-model="Editform.admin_name"
                maxlength="10"
                type="text">
            </el-input>
          </el-form-item>

          <el-form-item label="修改密码：" :label-width="formLabelWidth" prop="admin_password">
            <el-input
                placeholder="请输入新密码"
                show-word-limit
                type="password"
                maxlength="20"
                v-model="Editform.admin_password"></el-input>
            <small id="pwdHelp1" class="form-text text-muted">（新密码至少包含数字和英文，长度6-20）</small>
          </el-form-item>

          <el-form-item label="确认密码：" :label-width="formLabelWidth" prop="admin_password_again">
            <el-input
                placeholder="请再次输入新密码"
                show-word-limit
                type="password"
                maxlength="20"
                v-model="Editform.admin_password_again"></el-input>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="editSave('Editform')">修 改</el-button>
          <el-button @click="openCancelEdit">取 消</el-button>
        </span>
      </el-dialog>

      <!--添加弹窗-->
      <el-dialog
          title="创建管理员"
          :visible.sync="addialogVisible"
          width="40%"
          @close="handleClose">

        <!--       添加表单-->
        <el-form ref="Addform" :model="Addform" label-width="100px" :before-close="closeDiv">

          <el-form-item label="账号：" :label-width="formLabelWidth" prop="admin_account" required>
            <el-input
                placeholder="请输入管理员登录账号"
                show-word-limit
                v-model="Addform.admin_account"
                maxlength="10"
                type="text">
            </el-input>
            <small id="accountHelp" class="form-text text-muted">（账号至少包含数字和英文，长度5-10，不可重复）</small>
          </el-form-item>

          <el-form-item label="名称：" :label-width="formLabelWidth" prop="admin_name" required>
            <el-input
                placeholder="请输入管理员名"
                show-word-limit
                v-model="Addform.admin_name"
                maxlength="10"
                type="text">
            </el-input>
            <small id="nameHelp" class="form-text text-muted">（管理员名长度5-10，不可重复）</small>
          </el-form-item>

          <el-form-item label="密码：" :label-width="formLabelWidth" prop="admin_password" required>
            <el-input
                placeholder="请输入密码"
                show-word-limit
                type="password"
                maxlength="20"
                v-model="Addform.admin_password"></el-input>
            <small id="pwdHelp" class="form-text text-muted">（密码至少包含数字和英文，长度6-20）</small>
          </el-form-item>

          <el-form-item label="确认密码：" :label-width="formLabelWidth" prop="admin_password_again" required>
            <el-input
                placeholder="请再次输入密码"
                show-word-limit
                type="password"
                maxlength="20"
                v-model="Addform.admin_password_again"></el-input>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitAdd('Addform')">添 加</el-button>
          <el-button @click="cancel">取 消</el-button>
          <el-button @click="clearInput('Addform')">重 置</el-button>
        </span>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import {getAllAdminInfo,updateAdminInfo,deleteAdminByID,addAdmin} from '@/api/Admin'

export default {
  name: "information_main",
  data() {
    return {
      //搜索相关功能
      findName:'',
      adminContainerPage:0, // 分页的数据：当前页数
      adminContainerSize:0, // 分页的数据：每页的数量
      total:0,
      AdminData: [],
      showData:[],
      copyData:[],
      search_info:[],  //存放搜索到的容器
      multipleSelection: [],
      //  添加弹窗相关
      addialogVisible:false,
      Addform:{
        admin_account:'',
        admin_name:'',
        admin_password:'',
        admin_password_again:'',

      },
      //  编辑功能相关
      editdialogVisible:false,
      Editform:{
        admin_id:'',
        admin_account:'',
        admin_name:'',
        admin_password:'',
        admin_password_again:'',

      },
      formLabelWidth: '100px',





    }
  },

  methods: {
    //获取全部管理员信息
    init(){
      getAllAdminInfo({}).then(res=>{
        this.AdminData=res.data;
        this.copyData=res.data;
        this.getShowAdmin();
      })

    },
    getShowAdmin(){

      this.adminContainerSize=parseInt(10);
      this.showData = this.AdminData.slice((this.adminContainerPage - 1) * this.adminContainerSize, this.adminContainerPage * this.adminContainerSize);
      this.total=parseInt(this.AdminData.length);

    },
    //根据管理员名进行搜索
    searchByName(){

      var search=this.findName;
      if(search==""||search==null)
      {
        this.$msg.error('输入框不能为空！');
        this.init();
      }
      else {
        //执行本地过滤
        var search_list=this.copyData;
        this.search_info=[];  //装搜索结果的容器
        for(let i=0;i<search_list.length;i++)
        {
          if(search_list[i].admin_name.indexOf(search)>=0)
          {
            this.search_info.push(search_list[i]);
          }
        }
        if(this.search_info.length==0)
        {
          this.$msg.error('未找到相关结果,刷新一下~');
        }
        this.AdminData=this.search_info;
        //分页
        this.adminContainerPage=parseInt(1);
        this.getShowAdmin();

        //清空搜索框
        this.findName="";
      }

    },
    //分页
    //page改变时的回调函数，参数为当前页码
    handleCurrentChange(val) {

      console.log(`当前页: ${val}`);
      this.adminContainerPage= parseInt(val);
      this.getShowAdmin();

    },
    //编辑管理员信息  打开编辑弹窗
    edit(index, row) {

      this.editdialogVisible=true;

      // console.log(index);
      console.log(row);
      this.Editform.admin_account=row.admin_account;
      this.Editform.admin_name=row.admin_name;
      this.Editform.admin_id=row.admin_id;

    },
    //提交数据 修改
    editSave(formName)
    {

      //验证
      this.$refs[formName].validate((valid) => {
        if (valid) {

          //再次确认
          this.$confirm('确认修改?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            this.updateSave();

          }).catch(() => {
            this.$msg.error("修改失败！");
          });

        } else {
          this.$msg.error("修改失败！");
          return false;
        }
      });
    },
    //连接后端  进行修改
    updateSave(){

      var passReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/; //密码至少包含 数字和英文，长度6-20
      var nameReg=/^.{5,10}$/;  //管理员名长度5-10，不可重复

      if(this.Editform.admin_password.length<=0 && this.Editform.admin_password_again.length<=0 && this.Editform.admin_name.length<=0){
        this.$msg.warning('不能均为空！');
        return false;
      }
      if(this.Editform.admin_name.length>0)
      {
        if( !nameReg.test(this.Editform.admin_name)) {
          this.$msg.warning('管理员名长度为5-10！');
          this.Editform.admin_name="";
          return false;
        }
      }
      if(this.Editform.admin_password.length>0 && this.Editform.admin_password_again.length<=0){
        this.$msg.warning('请再次输入新密码！');
        return false;
      }
      if(this.Editform.admin_password.length<=0 && this.Editform.admin_password_again.length>0){
        this.$msg.warning('请输入新密码！');
        return false;
      }
      if(this.Editform.admin_password.length>0 && this.Editform.admin_password_again.length>0)
      {
        if(!(this.Editform.admin_password == this.Editform.admin_password_again))
        {
          this.$msg.warning('两次输入的密码不一致，请重新输入！');
          this.Editform.admin_password="";
          this.Editform.admin_password_again="";
          return false;
        }
        if(!passReg.test(this.Editform.admin_password))
        {
          this.$msg.warning('新密码至少包含数字和英文，长度为6-20！');
          this.Editform.admin_password="";
          this.Editform.admin_password_again="";
          return false;
        }
      }
      updateAdminInfo({
        admin_password: this.Editform.admin_password,
        admin_id:this.Editform.admin_id,
        admin_name:this.Editform.admin_name,
        token: window.sessionStorage.getItem('token')
      }).then(res=>{
        if(res.data.result==1)
        {
          this.$msg.success("修改成功！请重新登录！");
          //刷新表格数据
          this.init();
          //关闭弹窗
          this.editdialogVisible=false;
          sessionStorage.clear();
          this.$router.push({path:'/'});

        }
        else if(res.data.result==0)
        {
          this.$msg.warning("管理员名已存在，请勿重复！");
          this.Editform.admin_name="";
        }
        else{
          this.$msg.error("修改失败！");
        }
      })



    },
    //删除
    handleDelete(index, row) {

      //再次确认
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.deleteSave(row.admin_id);

      }).catch(() => {
        this.$msg.error("取消删除！");
      });

    },
    //连接后端，进行删除
    deleteSave(admin_id){

      deleteAdminByID({
        admin_id:admin_id,
        token: window.sessionStorage.getItem('token')
      }).then(res=>{
        if(res.data.code==1){
          this.$msg.success("删除成功！");
        }else{
          this.$msg.error("删除失败！");
        }
        this.init();
      })

    },
    //打开添加的弹窗
    addOpen(){
      this.addialogVisible=true;
    },
    submitAdd(formName){

      //验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //再次确认
          this.$confirm('确认创建?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            this.addSave();

          }).catch(() => {
            this.$msg.error("创建失败！");
          });

        }
        else {
          this.$msg.error("取消创建！");
          return false;
        }
      });

    },
    //连接后端 创建管理员
    addSave(){

      var accountReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,10}$/; //账号至少包含 数字和英文，长度5-10
      var passReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/; //密码至少包含 数字和英文，长度6-20
      var nameReg=/^.{5,10}$/ ;  //管理员名长度5-10，不可重复
     if(this.Addform.admin_account<=0)
      {
        this.$msg.warning('请输入管理员登录账号！')
      }
     else if(!accountReg.test(this.Addform.admin_account))
     {
       this.$msg.warning('账号至少包含数字和英文，长度为5-10！')
     }
      else if(this.Addform.admin_name<=0)
      {
        this.$msg.warning('请输入管理员名！')
      }
      else if( !nameReg.test(this.Addform.admin_name))
      {
        this.$msg.warning('管理员名长度为5-10！')
      }
      else if(this.Addform.admin_password<=0)
      {
        this.$msg.warning('请输入密码！')
      }
      else if(!passReg.test(this.Addform.admin_password))
      {
        this.$msg.warning('密码至少包含数字和英文，长度为6-20！')
      }
      else if(this.Addform.admin_password_again <= 0)
      {
        this.$msg.warning('请再次输入密码！')
      }
      else if(this.Addform.admin_password != this.Addform.admin_password_again)
      {
        this.$msg.warning('两次输入的密码不一致，请重新输入！')
      }
      else
      {
        addAdmin({
          admin_password: this.Addform.admin_password,
          admin_account:this.Addform.admin_account,
          admin_name:this.Addform.admin_name,
          token: window.sessionStorage.getItem('token')
        }).then(res=>{
          if(res.data.result==1){
            this.$msg.success("创建成功！");
            //刷新表格数据
            this.init();
            //关闭弹窗
            this.addialogVisible=false;
          }
          else if(res.data.result == -1){
            this.$msg.warning('该账户已存在，请勿重复创建！')
            this.Addform.admin_account="";    //清空输入框
          }
          else if(res.data.result == 0){
            this.$msg.warning('管理员名已存在，请勿重复！')
            this.Addform.admin_name='';
          }
          else{
            this.$msg.error("创建失败！");
          }
        })
      }


    },
    //重置按钮
    clearInput(formName){
      this.$refs[formName].resetFields();
    },
    //  关闭弹窗
    cancel() {
      this.addialogVisible = false
      // 点击取消按钮的时候清除输入框中的内容 清除验证
      //  this.$nextTick获取了节点之后进行操作
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });

    },
    openCancelEdit(){
      this.editdialogVisible = false
      // 点击取消按钮的时候清除输入框中的内容 清除验证
      //  this.$nextTick获取了节点之后进行操作
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Editform"].resetFields();
      });
    },
    // 右上角 × 取消按钮
    closeDiv() {

      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });

    },
    closeDivEdit(){
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Editform"].resetFields();
      });
    },
    //清空搜索框
    clearFindInput(){
      this.findName="";
      this.init();
    },
    handleClose(){
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });
    },
    handleCloseEdit(){
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Editform"].resetFields();
      });
    },
    //取消选择
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //  批量删除
    handleMultipleDelete(){

      if (this.multipleSelection == '') {
        this.$message.error('您未选中任何管理员，请重新操作！！！');
        return;
      }

      let checkArr = this.multipleSelection;  // multipleSelection存储了勾选到的数据
      let admin_ids = [];
      checkArr.forEach(function (item) {
        admin_ids.push(item.admin_id);
      });

      //再次确认
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        deleteAdminByID({
          admin_id:admin_ids,
          token: window.sessionStorage.getItem('token')
        }).then(res=>{
          if(res.data.code==1){
            this.$msg.success("批量删除成功！");
          }else{
            this.$msg.error("删除失败！");
          }
          this.init();
        });

      }).catch(() => {
        this.$msg.error("取消删除！");
      });


    },


  },
  created() {

    let _this=this;

    _this.adminContainerPage=parseInt(1);

    _this.init();

    _this.$refs.table.doLayout();


  },
}
</script>

<style scoped>
.btnfontClass{
  font-size: 15px;
}
.el-pagination {
  text-align: center;
}
.typeClass{
  font-size: 14px;
}

</style>
